package com.sdhs.examinemanage.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sdhs.businessfile.domain.BusinessFile;
import com.sdhs.businessfile.service.IBusinessFileService;
import com.sdhs.common.core.domain.entity.SysUser;
import com.sdhs.common.enums.BusinessTypeEnum;
import com.sdhs.common.utils.DateUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.common.utils.StringUtils;
import com.sdhs.examinemanage.domain.GcExamineManage;
import com.sdhs.examinemanage.domain.GcExamineManageScore;
import com.sdhs.examinemanage.mapper.GcExamineManageMapper;
import com.sdhs.examinemanage.service.IGcExamineManageService;
import com.sdhs.projectstart.domain.ProjectDept;
import com.sdhs.projectstart.mapper.ProjectDeptMapper;
import com.sdhs.system.domain.MessageInfoDO;
import com.sdhs.system.mapper.SysUserMapper;
import com.sdhs.system.service.IMessageInfoService;
import com.sdhs.workflow.utils.UnifyApiUtils;

import cn.hutool.core.util.StrUtil;

/**
 * 项目考核管理Service业务层处理
 * 
 * @author wanglei
 * @date 2025-03-27
 */
@Service
public class GcExamineManageServiceImpl implements IGcExamineManageService 
{
    @Autowired
    private GcExamineManageMapper gcExamineManageMapper;
    
    @Autowired
    private IBusinessFileService businessFileService;
    
    @Autowired
    private ProjectDeptMapper projectDeptMapper;
    
    @Autowired
    private IMessageInfoService messageInfoService;
    
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询项目考核管理
     * 
     * @param id 项目考核管理主键
     * @return 项目考核管理
     */
    @Override
    public GcExamineManage selectGcExamineManageById(Long id)
    {
    	GcExamineManage examineManage = gcExamineManageMapper.selectGcExamineManageById(id);
    	// 得分
    	List<GcExamineManageScore> scoreList = gcExamineManageMapper.selectScoreList(id);
    	examineManage.setScoreList(scoreList);
    	// 考核附件
    	List<BusinessFile> fileList = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_EXAMINE_MANAGE.getCode(), String.valueOf(id));
    	examineManage.setFileList(fileList);
    	// 申诉附件
    	List<BusinessFile> fileListAppeal = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_EXAMINE_APPEAL.getCode(), String.valueOf(id));
    	examineManage.setFileListAppeal(fileListAppeal);
    	return examineManage;
    }

    /**
     * 查询项目考核管理列表
     * 
     * @param gcExamineManage 项目考核管理
     * @return 项目考核管理
     */
    @Override
    public List<GcExamineManage> selectGcExamineManageList(GcExamineManage gcExamineManage)
    {
        return gcExamineManageMapper.selectGcExamineManageList(gcExamineManage);
    }

    /**
     * 新增项目考核管理
     * 
     * @param gcExamineManage 项目考核管理
     * @return 结果
     */
    @Override
    public int insertGcExamineManage(GcExamineManage gcExamineManage)
    {
    	setScore(gcExamineManage);
    	gcExamineManage.setAppealStatus("0");
		gcExamineManage.setCreater(SecurityUtils.getUsername());
        gcExamineManage.setCreateTime(DateUtils.getNowDate());
        int result = gcExamineManageMapper.insertGcExamineManage(gcExamineManage);
        gcExamineManageMapper.insertScoreBatch(gcExamineManage);
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_EXAMINE_MANAGE.getCode(), String.valueOf(gcExamineManage.getId()), gcExamineManage.getFileList());
        // 给项目经理发消息
        sendMsgExamine(gcExamineManage);
        return result;
    }
    
    /**
     * 给项目经理发消息
     * @param gcExamineManage
     */
    public void sendMsgExamine(GcExamineManage gcExamineManage) {
    	ProjectDept projectDept = projectDeptMapper.selectProjectDeptByProjectId(gcExamineManage.getProjectId());
        if (projectDept != null && StringUtils.isNotEmpty(projectDept.getManager())) {
        	String title = null;
        	String content = null;
        	if ("0".equals(gcExamineManage.getAppealStatus())) {
        		String titleTemplate = "项目考核：{}，总得分：{}";
    			String contentTemplate = "项目考核：{}，进度（20分）：{}，质量（20分）：{}，安全（15分）：{}，资金（15分）：{}，文明施工（10分）：{}，综合管理（20分）：{}，加分项（15分）：{}，总得分：{}";
    			title = StrUtil.format(titleTemplate, gcExamineManage.getProjectName(), gcExamineManage.getTotalScore());
    			content = StrUtil.format(contentTemplate, gcExamineManage.getProjectName(), gcExamineManage.getProgress(), gcExamineManage.getQuality(), 
    					gcExamineManage.getSafe(), gcExamineManage.getCapitalCost(), gcExamineManage.getCivilizedConstruction(), gcExamineManage.getGeneralManage(), 
    					gcExamineManage.getPluses(), gcExamineManage.getTotalScore());
            } else if ("2".equals(gcExamineManage.getAppealStatus())) {
            	String titleTemplate = "项目考核：{}，总得分：{}，申诉已办理";
            	title = StrUtil.format(titleTemplate, gcExamineManage.getProjectName(), gcExamineManage.getTotalScore());
            	if (StringUtils.isNotEmpty(gcExamineManage.getHandleOpinion())) {
            		String contentTemplate = "项目考核：{}，进度（20分）：{}，质量（20分）：{}，安全（15分）：{}，资金（15分）：{}，文明施工（10分）：{}，综合管理（20分）：{}，加分项（15分）：{}，总得分：{}，申诉已办理，办理意见：{}";
            		content = StrUtil.format(contentTemplate, gcExamineManage.getProjectName(), gcExamineManage.getProgress(), gcExamineManage.getQuality(), 
        					gcExamineManage.getSafe(), gcExamineManage.getCapitalCost(), gcExamineManage.getCivilizedConstruction(), gcExamineManage.getGeneralManage(), 
        					gcExamineManage.getPluses(), gcExamineManage.getTotalScore(), gcExamineManage.getHandleOpinion());
            	} else {
            		String contentTemplate = "项目考核：{}，进度（20分）：{}，质量（20分）：{}，安全（15分）：{}，资金（15分）：{}，文明施工（10分）：{}，综合管理（20分）：{}，加分项（15分）：{}，总得分：{}，申诉已办理";
            		content = StrUtil.format(contentTemplate, gcExamineManage.getProjectName(), gcExamineManage.getProgress(), gcExamineManage.getQuality(), 
        					gcExamineManage.getSafe(), gcExamineManage.getCapitalCost(), gcExamineManage.getCivilizedConstruction(), gcExamineManage.getGeneralManage(), 
        					gcExamineManage.getPluses(), gcExamineManage.getTotalScore());
            	}
            }
			String type = "gc_examine_manage";
			Integer msgCount = messageInfoService.countByContent(title, content, projectDept.getManager());
			if (msgCount == 0) {
				// 我的消息
				List<MessageInfoDO> myMsgList = messageInfoService.getMsgList(title, content, gcExamineManage.getId(), type, projectDept.getManager());
				messageInfoService.sendMsgBatch(myMsgList);
				// 企业微信
				List<String> users = new ArrayList<String>();
				users.add(projectDept.getUserId());
				UnifyApiUtils.sendWXWORKTextMsg(title, users, "system", content);
			}
        }
    }
    
    /**
     * 项目经理提起申诉，给工程管理中心发消息
     * @param gcExamineManage
     */
    public void sendMsgAppeal(GcExamineManage gcExamineManage) {
    	SysUser sysUser = sysUserMapper.checkUserNameUnique(gcExamineManage.getCreater());
    	if (sysUser != null && StringUtils.isNotEmpty(sysUser.getUserId())) {
    		String titleTemplate = "项目考核：{}，总得分：{}，项目经理提起申诉";
			String contentTemplate = "项目考核：{}，进度（20分）：{}，质量（20分）：{}，安全（15分）：{}，资金（15分）：{}，文明施工（10分）：{}，综合管理（20分）：{}，加分项（15分）：{}，总得分：{}，项目经理提起申诉，申诉原因：{}";
			String title = StrUtil.format(titleTemplate, gcExamineManage.getProjectName(), gcExamineManage.getTotalScore());
			String content = StrUtil.format(contentTemplate, gcExamineManage.getProjectName(), gcExamineManage.getProgress(), gcExamineManage.getQuality(), 
					gcExamineManage.getSafe(), gcExamineManage.getCapitalCost(), gcExamineManage.getCivilizedConstruction(), gcExamineManage.getGeneralManage(), 
					gcExamineManage.getPluses(), gcExamineManage.getTotalScore(), gcExamineManage.getAppealReason());
			String type = "gc_examine_manage";
			Integer msgCount = messageInfoService.countByContent(title, content, gcExamineManage.getCreater());
			if (msgCount == 0) {
				// 我的消息
				List<MessageInfoDO> myMsgList = messageInfoService.getMsgList(title, content, gcExamineManage.getId(), type, gcExamineManage.getCreater());
				messageInfoService.sendMsgBatch(myMsgList);
				// 企业微信
				List<String> users = new ArrayList<String>();
				users.add(sysUser.getUserId());
				UnifyApiUtils.sendWXWORKTextMsg(title, users, "system", content);
			}
    	}
    }
    
    /**
     * 计算进度、质量、安全、资金、文明施工、综合管理、加分项，得分
     * @param gcExamineManage
     */
    public void setScore(GcExamineManage gcExamineManage) {
    	List<GcExamineManageScore> scoreList = gcExamineManage.getScoreList();
    	// 进度
    	List<GcExamineManageScore> progressList = scoreList.subList(0, 3);
    	BigDecimal progress = progressList.stream().map(GcExamineManageScore::getScore).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    	gcExamineManage.setProgress(progress);
    	// 质量
    	List<GcExamineManageScore> qualityList = scoreList.subList(3, 6);
    	BigDecimal quality = qualityList.stream().map(GcExamineManageScore::getScore).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    	gcExamineManage.setQuality(quality);
    	// 安全
    	List<GcExamineManageScore> safeList = scoreList.subList(6, 9);
    	BigDecimal safe = safeList.stream().map(GcExamineManageScore::getScore).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    	gcExamineManage.setSafe(safe);
    	// 资金
    	List<GcExamineManageScore> capitalCostList = scoreList.subList(9, 11);
    	BigDecimal capitalCost = capitalCostList.stream().map(GcExamineManageScore::getScore).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    	gcExamineManage.setCapitalCost(capitalCost);
    	// 文明施工
    	List<GcExamineManageScore> civilizedConstructionList = scoreList.subList(11, 14);
    	BigDecimal civilizedConstruction = civilizedConstructionList.stream().map(GcExamineManageScore::getScore).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    	gcExamineManage.setCivilizedConstruction(civilizedConstruction);
    	// 综合管理
    	List<GcExamineManageScore> generalManageList = scoreList.subList(14, 19);
    	BigDecimal generalManage = generalManageList.stream().map(GcExamineManageScore::getScore).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    	gcExamineManage.setGeneralManage(generalManage);
    	// 加分项
    	List<GcExamineManageScore> plusesList = scoreList.subList(19, 23);
    	BigDecimal pluses = plusesList.stream().map(GcExamineManageScore::getScore).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    	gcExamineManage.setPluses(pluses);
    }

    /**
     * 修改项目考核管理
     * 
     * @param gcExamineManage 项目考核管理
     * @return 结果
     */
    @Override
    public int updateGcExamineManage(GcExamineManage gcExamineManage)
    {
    	setScore(gcExamineManage);
		gcExamineManage.setUpdater(SecurityUtils.getUsername());
        gcExamineManage.setUpdateTime(DateUtils.getNowDate());
        int result = gcExamineManageMapper.updateGcExamineManage(gcExamineManage);
        gcExamineManageMapper.deleteScore(gcExamineManage.getId());
        gcExamineManageMapper.insertScoreBatch(gcExamineManage);
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_EXAMINE_MANAGE.getCode(), String.valueOf(gcExamineManage.getId()), gcExamineManage.getFileList());
        // 给项目经理发消息
        sendMsgExamine(gcExamineManage);
        return result;
    }
    
    /**
     * 项目考核申诉
     * 
     * @param gcExamineManage 
     * @return 结果
     */
    @Override
    public int updateGcExamineManageAppeal(GcExamineManage gcExamineManage)
    {
    	gcExamineManage.setAppealDate(new Date());
    	gcExamineManage.setAppealStatus("1");
    	gcExamineManage.setUpdater(SecurityUtils.getUsername());
        gcExamineManage.setUpdateTime(DateUtils.getNowDate());
        int result = gcExamineManageMapper.updateGcExamineManage(gcExamineManage);
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_EXAMINE_APPEAL.getCode(), String.valueOf(gcExamineManage.getId()), gcExamineManage.getFileListAppeal());
        // 项目经理提起申诉，给工程管理中心发消息
        sendMsgAppeal(gcExamineManage);
        return result;
    }
    
    /**
     * 项目考核申诉反馈
     * 
     * @param gcExamineManage 
     * @return 结果
     */
    @Override
    public int updateGcExamineManageAppealFeedback(GcExamineManage gcExamineManage)
    {
    	gcExamineManage.setAppealStatus("2");
    	gcExamineManage.setUpdater(SecurityUtils.getUsername());
        gcExamineManage.setUpdateTime(DateUtils.getNowDate());
        int result = gcExamineManageMapper.updateGcExamineManage(gcExamineManage);
        // 给项目经理发消息
        sendMsgExamine(gcExamineManage);
        return result;
    }

    /**
     * 批量删除项目考核管理
     * 
     * @param ids 需要删除的项目考核管理主键
     * @return 结果
     */
    @Override
    public int deleteGcExamineManageByIds(Long[] ids)
    {
        return gcExamineManageMapper.deleteGcExamineManageByIds(ids);
    }

    /**
     * 删除项目考核管理信息
     * 
     * @param id 项目考核管理主键
     * @return 结果
     */
    @Override
    public int deleteGcExamineManageById(Long id)
    {
        return gcExamineManageMapper.deleteGcExamineManageById(id);
    }
}
